package cn.yzgy.yzgyoa.common.handler;

import cn.yzgy.yzgyoa.common.crsp.StatusCode;
import cn.yzgy.yzgyoa.common.crsp.Urmf;
import cn.yzgy.yzgyoa.common.service.impl.SysAlarmServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * SQL异常Handler
 * @author Yqsen
 * @since 2019-10-18 09:01:18
 */
@Slf4j
@Order(-999999)
@ControllerAdvice
@RestControllerAdvice
public class SqlExceptionHandler {

    @Autowired
    private SysAlarmServiceImpl sysAlarmService;

    /**
     * 此异常表示违反了一个完整性约束（外键、主键或唯一键）。
     * 一般为主键或UNIQUE键重复所致的异常
     *
     * @param e 异常对象
     * @param request 请求信息
     * @return 异常信息
     */
    @Order(-1)
    @ResponseBody
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Urmf sqlIntergrityExceptionHandler(SQLIntegrityConstraintViolationException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        log.error("SQL_CONSTRAINT_EXCEPTION_HANDLER: StackTrace:{} Message:{}", e.getStackTrace()[0], e.getMessage());
        sysAlarmService.saveExceptions(e);
        return Urmf.fail(request.getRequestURI(), StatusCode.SQL_DUPLICATE_KEY, e.toString());
    }

}
